<?php
namespace App\Console\Commands;

use App\Models\AdminRegion;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class ImportRegions extends Command
{
    protected $signature = 'import:regions';
    protected $description = 'Import region data from pca-code.json';

    public function handle()
    {
        $json = file_get_contents(base_path('/public/pca-code.json'));
        $data = json_decode($json, true);

        $regions = [];
        $this->parse($data, 1, '0', $regions);

        AdminRegion::truncate();
        AdminRegion::insert($regions);

        $this->info("导入完成，共导入 " . count($regions) . " 条区域数据。");
    }

    private function parse(array $items, int $level, string $parentCode, array &$result)
    {
        foreach ($items as $item) {
            $result[] = [
                'id'        => $item['code'],
                'name'        => $item['name'],
                'parent_id' => $parentCode,
                'level'       => $level,
                'created_at'  => now(),
                'updated_at'  => now(),
            ];

            if (!empty($item['children'])) {
                $this->parse($item['children'], $level + 1, $item['code'], $result);
            }
        }
    }
}

